<template>
    <div class="app">
        <!-- 这里是nav -->
        <my-nav></my-nav>
        <!-- 这里是头部 -->
        <my-head></my-head>

        <div class="content">
            <div class="friend">
                <div class="head">
                    <label tabindex="0" class="btn btn-ghost btn-circle avatar" style="margin-top: 10px;margin-left:20px">
                        <div class="w-10 rounded-full">
                            <img :src="head" />
                        </div>
                    </label>

                    <div class="name" style="margin-top: -38px;margin-left:80px;font-weight:bolder">
                        #Admin
                    </div>

                    <div class="indicator" style="margin-left:240px">
                        <span class="indicator-item badge badge-secondary" style="margin-left:200px;margin-top:-30px">{{
                            unreadCount }}</span>
                    </div>
                </div>

                <input type="text" v-model="search" placeholder="搜索用户"
                    class="input input-bordered input-error w-full max-w-xs"
                    style="width: 260px;margin-left:15px;margin-top:10px;margin-bottom:15px" />

                <br>
                <a style="color: #97A3B6;font-size:12px;margin-top:40px;font-weight:bolder;margin-left:20px">用户列表</a>

                <div class="overflow-x-auto w-full" style="width: 90%;">
                    <table class="table w-full">
                        <!-- head -->
                        <tbody>
                            <!-- row 1 -->
                            <tr class="hover" v-for="item in allUser" :key="item.id">
                                <td @click="changeUser(item.id)">
                                    <div class="flex items-center space-x-3">
                                        <div class="avatar">
                                            <div class="mask mask-squircle w-12 h-12">
                                                <img :src="item.head" alt="Avatar Tailwind CSS Component" />
                                            </div>
                                        </div>
                                        <div>
                                            <div class="font-bold">{{ item.id }}</div>
                                        </div>
                                        <div class="badge badge-secondary" style="margin-left: 100px;">{{ item.read }}</div>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>



            <div class="chat">
                <div class="head">
                    <div class="avatar-group -space-x-6" style="margin-top:5px;margin-left:20px" v-if="head && u_head">
                        <div class="avatar">
                            <div class="w-12">
                                <img :src="head" />
                            </div>
                        </div>
                        <div class="avatar">
                            <div class="w-12">
                                <img :src="u_head" />
                            </div>
                        </div>
                    </div>

                    <div class="flex-1" style="margin-top: -50px;text-align:center">
                        <a class="btn btn-ghost normal-case text-xl">{{ u }}</a>
                    </div>
                </div>

                <div class="body" style="overflow: auto; background-color: #F2F5F9;" ref="body">
                    <a v-for="(message, index) in  u_message " :key="index" v-if="u">
                        <div class="she" style="margin-top: 20px;margin-left:15px" v-if="message.from_id != id">
                            <!-- 判断是发送图片 还是信息 -->
                            <a v-if="!message.content.startsWith('data')">
                                <label tabindex="0" class="btn btn-ghost btn-circle avatar">
                                    <div class="w-10 rounded-full">
                                        <img :src="u_head" />
                                    </div>
                                </label>
                                <div class="chat-bubble chat-bubble-secondary"
                                    style="margin-top:-50px;margin-left:58px;max-height:200px;">{{ message.content }}</div>
                                <div class="chat-footer opacity-50" style="margin-top:0px;margin-left:60px">
                                    {{ message.time }}
                                </div>
                            </a>

                            <a v-else>
                                <div class="she" style="margin-top: 20px;margin-left:0px">
                                    <label tabindex="0" class="btn btn-ghost btn-circle avatar">
                                        <div class="w-10 rounded-full">
                                            <img :src="u_head" />
                                        </div>
                                    </label>
                                    <div style="margin-top:-50px;margin-left:58px;max-height:200px;"><img
                                            :src="message.content" style="width: 100px;"></div>
                                    <div class="chat-footer opacity-50" style="margin-top:0px;margin-left:60px">
                                        {{ message.time }}
                                    </div>
                                </div>
                            </a>
                        </div>


                        <div class="me" style="margin-top: 20px;margin-right:15px;text-align:right;" v-else>
                            <a v-if="!message.content.startsWith('data')">
                                <label tabindex="0" class="btn btn-ghost btn-circle avatar"
                                    style="float: right;margin-left:8px">
                                    <div class="w-10 rounded-full">
                                        <img :src="head" />
                                    </div>
                                </label>
                                <div class="chat-bubble chat-bubble-primary" style="float:right">
                                    {{ message.content }}</div>
                                <div class="chat-footer opacity-50"
                                    style="margin-top:0px;margin-right:10px;clear:both;margin-right:55px">
                                    {{ message.time }}
                                </div>
                            </a>

                            <a v-else>
                                <div class="me" style="margin-top: 20px;margin-right:0px;text-align:right;">
                                    <label tabindex="0" class="btn btn-ghost btn-circle avatar"
                                        style="float: right;margin-left:8px">
                                        <div class="w-10 rounded-full">
                                            <img :src="head" />
                                        </div>
                                    </label>
                                    <div style="float:right">
                                        <img :src="message.content" style="width: 100px;">
                                    </div>
                                    <div class="chat-footer opacity-50"
                                        style="margin-top:0px;margin-right:10px;clear:both;margin-right:55px">
                                        {{ message.time }}
                                    </div>
                                </div>
                            </a>
                        </div>
                    </a>
                </div>
                <div class="data" style="border-radius: 0px;">
                    <label for="my-modal" class="btn" style="margin-top: 5px;float:left">图片</label>

                    <input type="checkbox" id="my-modal" class="modal-toggle" />
                    <div class="modal">
                        <div class="modal-box">
                            <h3 class="font-bold text-lg">选择上传的图片</h3>
                            <p class="py-4"><input type="file" class="file-input file-input-bordered w-full max-w-xs"
                                    style="margin-left:60px;" @change="onFileChange" /></p>
                            <div class="modal-action">
                                <label for="my-modal" class="btn" @click="clearFile">取消</label>
                                <label for="my-modal" class="btn" @click="sendImages">确定</label>
                            </div>
                        </div>
                    </div>

                    <input type="text" v-model="message" placeholder="message" @keyup.enter="sendMessage"
                        style="width: 680px;margin-left:70px;margin-top:-42px;float:left; background-color: #F2F5F9;height:40px;border-radius: 4px;padding-left:20px" />

                    <button class="btn" style=";float:left;margin-left:770px;margin-top:-46px"
                        @click="sendMessage">Send</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import MyHead from "../../components/head.vue"
import MyNav from "../../components/nav.vue"

export default {
    name: "chat",
    data() {
        return {
            head: "https://avatars.githubusercontent.com/u/26568691?s=120&v=4",
            socket: null, //socket连接信息
            id: "admin",//假设管理端的ID是admin
            message: '', //存储消息
            messages: [], //存储所有消息 包括接受的消息
            selectedFile: '', //存储图片信息
            groupedMessages: {},// add this line to initialize groupedMessages
            user: [],//储存用户信息
            unreadCount: 0, //所有未读消息的信息数
            search: '',   //搜索用户的关键词
            allUser: [],    //存储所有用户
            u: '',         //存储对方用户
            u_head: '',    //存储对方用户的头像
            u_message: [], //存储用户聊天记录
        }
    },

    created() {
        this.initWebSocket();
    },
    components: {
        'my-head': MyHead,
        'my-nav': MyNav,
    },
    beforeCreate() {
        this.initWebSocket();
    },
    methods: {
        initWebSocket() {
            //开始建立ws连接之前从浏览器本地缓存 获取之前聊天数据 实现聊天记录保存
            const user_messages = localStorage.getItem('user_messages')
            //将获取到之前的聊天记录实现 缓存
            this.messages = user_messages ? JSON.parse(user_messages) : [];
            //获取该用户
            this.groupMessagesByFromId()

            this.socket = new WebSocket('ws://localhost:9999/ws?id=' + this.id);
            this.socket.onmessage = event => {
                let data = JSON.parse(event.data);
                //说明是用户发来的信息
                this.$set(this.messages, this.messages.length, data);
                this.$set(this.u_message, this.u_message.length, data);
                this.groupMessagesByFromId();
                this.updateUnreadCount(); // 添加这行代码

                this.scrollToBottom();
                //收到消息将 消息存储到本地缓存
                const jsonItems = JSON.stringify(this.messages);
                // 将JSON字符串存储到localStorage
                localStorage.setItem('user_messages', jsonItems);
            };
        },
        sendMessage() {
            if (this.message.trim() !== '' && this.socket.readyState === WebSocket.OPEN) {
                let msg = {
                    from_id: this.id,
                    to_id: this.u,
                    content: this.message,
                    isRead: true, //是否查看
                    time: new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
                };
                this.messages.push(msg);
                this.u_message.push(msg)
                this.socket.send(JSON.stringify(msg));
                this.message = '';
                this.scrollToBottom();
                this.allUser = this.user //暂时储存
                this.changeUser(this.u)

                //收到消息将 消息存储到本地缓存
                const jsonItems = JSON.stringify(this.messages);
                // 将JSON字符串存储到localStorage
                localStorage.setItem('user_messages', jsonItems);
            }
        },
        sendImages() {
            if (this.selectedFile.trim() !== '' && this.socket.readyState === WebSocket.OPEN) {
                let msg = {
                    from_id: this.id,
                    to_id: this.u,
                    content: this.selectedFile,
                    isRead: true, //是否查看 在自己这里是查看的 但是在对方那里并未查看
                    time: new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
                };
                this.messages.push(msg);
                this.u_message.push(msg)
                this.socket.send(JSON.stringify(msg));
                this.selectedFile = '';
                this.scrollToBottom();
                this.changeUser(this.u)

                //收到消息将 消息存储到本地缓存
                const jsonItems = JSON.stringify(this.messages);
                // 将JSON字符串存储到localStorage
                localStorage.setItem('user_messages', jsonItems);

            }
        },
        groupMessagesByFromId() {
            const groupedMessages = {};
            this.messages.forEach(message => {
                if (message.from_id !== 'admin') {
                    const key = message.from_id;
                    if (!groupedMessages[key]) {
                        groupedMessages[key] = [];
                    }
                    groupedMessages[key].push(message);
                } else if (message.to_id !== 'admin') {
                    const key = message.to_id;
                    if (!groupedMessages[key]) {
                        groupedMessages[key] = [];
                    }
                    groupedMessages[key].push(message);
                }
            });
            //获取所有的keys 即获取所有用户的头像
            var keys = Object.keys(groupedMessages).filter(key => key.trim() !== '');

            // 将键包装成一个对象
            var payload = { keys: keys };
            console.log(keys);
            //  通过这些keys去获取用户信息
            this.$http.post("/admin/FindUser", payload).then((rep) => {
                this.user = rep.data.message;
                this.updateUnreadCount()
                this.unreadCount = 0
                //遍历获取所有未读数
                for (let index = 0; index < this.user.length; index++) {
                    this.unreadCount += parseInt(this.user[index].read);
                }

                this.allUser = this.user
                console.log(this.allUser);
            }).catch((rep) => {
                console.log(rep);
            })
        },
        scrollToBottom() {
            this.$nextTick(() => {
                this.$refs.body.scrollTop = this.$refs.body.scrollHeight;
            });
        },
        onFileChange(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.selectedFile = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        },
        clearFile() {
            this.selectedFile = '';
        },
        updateUnreadCount() {
            for (var i = 0; i < this.user.length; i++) { //遍历用户
                var number = 0
                for (var j = 0; j < this.messages.length; j++) { //遍历消息
                    if (this.messages[j].from_id == this.user[i].id && this.messages[j].isRead == false) {
                        number++
                    }
                }
                if (number == 0) {
                    this.$set(this.user[i], 'read', '0')
                } else if (number > 99) {
                    this.$set(this.user[i], 'read', '+99')
                } else {
                    this.$set(this.user[i], 'read', number.toString()) // 将 number 转换为字符串
                }
            }
        },
        changeUser(id) {
            //将这个用户的消息显示已读
            for (let index = 0; index < this.messages.length; index++) {
                if (this.messages[index].from_id == id && this.messages[index].isRead == false) {
                    this.messages[index].isRead = true
                }
            }
            this.u = id  //更改当前用户
            //获取该用户的头像
            for (let index = 0; index < this.user.length; index++) {
                if (this.user[index].id == id) {
                    this.u_head = this.user[index].head
                }
            }
            this.u_message = [] //重置聊天记录
            //获取该用户的聊天记录
            for (let index = 0; index < this.messages.length; index++) {
                if (this.messages[index].from_id == id || this.messages[index].to_id == id) {
                    this.u_message.push(this.messages[index])
                }
            }

            this.updateUnreadCount();

            //获取所有
            // unreadCount: 0
            this.unreadCount = 0 //重置
            for (let index = 0; index < this.messages.length; index++) {
                if (this.messages[index].isRead == false) {
                    this.unreadCount++
                }
            }
        }
    },
    watch: {
        messages: { //如果收到信息了
            handler(newUsers, oldUsers) {
                //实现获取用户的信息
                for (var i = 0; i < this.user.length; i++) { //遍历用户
                    var number = 0
                    for (var j = 0; j < newUsers.length; j++) { //遍历消息
                        if (this.messages[j].from_id == this.user[i].id && this.messages[j].isRead == false) {
                            number++
                        }
                    }
                    if (number == 0) {
                        this.$set(this.user[i], 'read', '0')
                    } else if (number > 99) {
                        this.$set(this.user[i], 'read', '+99')
                    } else {
                        this.$set(this.user[i], 'read', number)
                    }
                }
            }
        },
        search: {
            handler(newUsers, oldUsers) { //检测admin想要搜查的用户信息
                //实现
                if (newUsers.length == 0) {
                    this.allUser = this.user
                } else {
                    this.allUser = []
                    for (let index = 0; index < this.user.length; index++) {
                        if (this.user[index].id.includes(this.search)) {
                            this.allUser.push(this.user[index]);
                        }
                    }
                }
            }
        }
    },

}
</script>

<style scoped>
* {
    -webkit-user-select: none;
    /*webkit浏览器*/
    -khtml-user-select: none;
    /*早期浏览器*/
    -moz-user-select: none;
    /*火狐*/
    -ms-user-select: none;
    /*IE10*/
    user-select: none;
}

.content {
    width: 85%;
    height: 100vh;
    margin-left: 15.6%;
    overflow: auto;
    border: 1px solid #E3E8EF;
}

.friend {
    margin-top: 10vh;
    border-bottom: 1px solid #E3E8EF;
    border-right: 1px solid #E3E8EF;
    width: 25%;
    height: 90vh;
    float: left;
    overflow: auto;
}

.friend .head {
    width: 100%;
    height: 70px;
    border-bottom: 1px solid #E3E8EF;
    border-top: 1px solid #E3E8EF;
}

.chat {
    margin-top: 10vh;
    border-bottom: 1px solid #E3E8EF;
    width: 75%;
    height: 90vh;
    float: right;
}

.chat .head {
    width: 203%;
    height: 70px;
    border-bottom: 1px solid #E3E8EF;
    border-top: 1px solid #E3E8EF;
    margin-top: -4px;
}

.body {
    width: 202%;
    height: 74vh;
    border: 1px solid #E3E8EF;
    margin-top: 66px;
    margin-left: -444px;
}

.input {
    border: 1px solid #E3E8EF;
    width: 202%;
}
</style>